package com.wing.cms.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wing.cms.dao.ChannelDao;
import com.wing.cms.dao.PlaceholderDao;
import com.wing.cms.dao.Portlet1Dao;
import com.wing.cms.dao.TemplateDao;
import com.wing.cms.domain.Placeholder;
import com.wing.cms.domain.Portlet;
import com.wing.cms.domain.Portlet1;
import com.wing.cms.domain.Template;
import com.wing.common.util.GUID;
/**
 * 
 * @author wyf
 * 
 */
@Service
@Transactional
public class Portlet1Manager {
	@Autowired
	private Portlet1Dao portlet1dao;
	@Autowired
	private PlaceholderDao placeholderDao;
	@Autowired
	private ChannelDao channelDao;
	@Autowired
	private TemplateDao templateDao;


	/**
	 * 通过id得到对象
	 *
	 * @param  id
	 * @return pObject
	 */
	public Portlet1 findById(String id){
		return portlet1dao.findById(id);	 
	}
	
	/**
	 * 保存对象
	 *
	 * @param  Portlet
	 */
	public void savePortletInfo(Portlet1 Portlet1,String horderChannelId,String placeholderId,String portletype,String siteId){
		if(Portlet1.getId() == null ||  "".equals(Portlet1.getId())){
			String portletInstanceId = new GUID().toString();
			Portlet1.setId(portletInstanceId);
			portlet1dao.insert(Portlet1);
			
			Placeholder ph = new Placeholder();
			ph.setId(new GUID().toString());
			ph.setPlaceholderid(placeholderId);
			ph.setPortletid(portletInstanceId);
			if(horderChannelId.indexOf("a,")!= -1){
				//虚拟的布局id,布局文件已经写死article.jsp
				 ph.setLayoutid("articleLayId");
				 ph.setChannelid(horderChannelId.substring(0, horderChannelId.indexOf(","))+","+siteId);
			}else if(horderChannelId.indexOf("p,")!= -1){
				//虚拟的布局id,布局文件已经写死product.jsp
				ph.setLayoutid("productayId");
				ph.setChannelid(horderChannelId.substring(0, horderChannelId.indexOf(","))+","+siteId);
			}else{
				ph.setLayoutid(channelDao.findById(horderChannelId).getLayout());
				 ph.setChannelid(horderChannelId);
			}
			ph.setPortletype(portletype);
			ph.setOrder_num((int)System.currentTimeMillis());
			placeholderDao.insert(ph);
		}else{
			portlet1dao.update(Portlet1);
		}
	}

	public String findTemplateFile(String portletId) {
		Portlet1 p = portlet1dao.findById(portletId);
		if(p==null){
			return "error.ftl";
		}
		String templateId = portlet1dao.findById(portletId)
				.getTemplateid();
		Template  t =templateDao.findById(templateId);
		if(t==null){
			return "error.ftl";
		}
		return t.getFtlpath();
	}
	
	//删除
	public void deletePortlet(String id) {
		placeholderDao.deleteByPortletId(id);
		portlet1dao.delete(id);
	}
}



